<template>
  <div class="info-container">
    <!-- 搜索框和发布按钮 -->
    <div class="search-container">
      <el-input v-model="searchKeyword" placeholder="搜索文章..." clearable @keyup.enter="handleSearch"
        style="width: 300px">
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>

      <!-- 发布按钮（仅管理员可见） -->
      <el-button v-if="isAdmin" type="primary" @click="dialogVisible = true" class="publish-button">
        发布新信息
      </el-button>
    </div>

    <!-- 发布对话框 -->
    <el-dialog v-model="dialogVisible" title="发布信息" width="50%">
      <el-form :model="newArticle" label-width="80px">
        <el-form-item label="类型" required>
          <el-select v-model="newArticle.type" placeholder="请选择信息类型">
            <el-option label="院校招生" value="admission"></el-option>
            <el-option label="专业介绍" value="major"></el-option>
            <el-option label="考试大纲" value="exam"></el-option>
            <el-option label="参考书目" value="book"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" required>
          <el-input v-model="newArticle.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input v-model="newArticle.content" type="textarea" :rows="5"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitArticle">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文章卡片列表（保持不变） -->
    <div class="article-list">
      <el-card v-for="(article, index) in articles" :key="index" class="article-card" :class="`type-${article.type}`"
        @click="showArticleDetail(article)">
        <template #header>
          <div class="card-header">
            <span class="type-tag">{{ getTypeName(article.type) }}</span>
            <h3>{{ article.title }}</h3>
            <el-button v-if="isAdmin" type="danger" size="small" circle class="delete-btn"
              @click.stop="confirmDelete(article.id)">
              <el-icon>
                <Close />
              </el-icon>
            </el-button>
          </div>
        </template>
        <div class="card-content">
          <p v-if="article.content.length <= 20">{{ article.content }}</p>
          <p v-else>{{ article.content.slice(0, 20) }}...</p>
        </div>
        <div class="card-footer">
          <el-tag type="primary" style="float: left;">{{ article.author }}</el-tag>
          <span class="date">{{ formatDate(article.date) }}</span>
        </div>
      </el-card>
    </div>
  </div>
  <div class="pagination-container">
    <el-pagination v-model:current-page="pagination.currentPage" :page-size="pagination.pageSize"
      :total="pagination.total" layout="prev, pager, next, jumper" @current-change="handlePageChange" />
  </div>

  <!-- 文章详情抽屉 -->
  <el-drawer v-model="detailDrawerVisible" title="文章详情" direction="rtl" size="40%">
    <div class="article-detail">
      <h2>{{ currentArticle.title }}</h2>
      <div class="meta-info">
        <el-tag :type="getTagType(currentArticle.type)">
          {{ getTypeName(currentArticle.type) }}
        </el-tag>
        <span class="date">{{ formatDate(currentArticle.date) }}</span>
      </div>
      <div class="content">
        {{ currentArticle.content }}
      </div>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import { computed, ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import http from '@/utils/http'
import { Search } from '@element-plus/icons-vue'

interface Article {
  id: number
  type: string
  title: string
  content: string
  created_at: string
  date: Date
  author: string
}

const userStore = useUserStore()
const isAdmin = computed(() => userStore.user?.role === 'admin')

const articles = ref<Article[]>([])
const dialogVisible = ref(false)
const loading = ref(false)
const pagination = ref({
  currentPage: 1,
  pageSize: 6,
  total: 0
})

// 获取文章列表
const fetchArticles = async () => {
  try {
    loading.value = true
    const response = await http.get('/information/articles/', {
      params: {
        page: pagination.value.currentPage,
        size: pagination.value.pageSize,
        search: searchKeyword.value
      }
    })

    // 根据后端返回结构调整
    articles.value = response.data.items.map((item: any) => ({
      id: item.id,
      type: item.type,
      title: item.title,
      content: item.content,
      date: new Date(item.created_at),
      views: item.views,
      author: item.author
    }))
    pagination.value.total = response.data.total
  } catch (error) {
    ElMessage.error('获取文章列表失败')
    console.error('API错误:', error)
  } finally {
    loading.value = false
  }
}

// 发布文章
const newArticle = ref({
  type: '',
  title: '',
  content: ''
})

const submitArticle = async () => {
  if (!newArticle.value.type || !newArticle.value.title || !newArticle.value.content) {
    return ElMessage.error('请填写完整信息')
  }

  try {
    const response = await http.post('/information/articles/create/', {
      type: newArticle.value.type,
      title: newArticle.value.title,
      content: newArticle.value.content
    })

    if (response) {
      ElMessage.success('文章发布成功')
      dialogVisible.value = false
      newArticle.value = { type: '', title: '', content: '' }
      fetchArticles()
    } else {
      ElMessage.error('发布失败')
    }
  } catch (error) {
    ElMessage.error('发布失败: ' + error)
  }
}

// 删除文章
const confirmDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await http.delete(`/information/articles/${id}/delete/`)
    ElMessage.success('删除成功')
    fetchArticles()
  } catch (error) {
    // 用户取消删除
  }
}

// 初始化加载数据
onMounted(() => {
  fetchArticles()
})

// 分页改变
const handlePageChange = (page: number) => {
  pagination.value.currentPage = page
  fetchArticles()
}

const getTypeName = (type: string) => {
  const map: Record<string, string> = {
    'admission': '院校招生',
    'major': '专业介绍',
    'exam': '考试大纲',
    'book': '参考书目'
  };
  return map[type] || '其他';
};

const formatDate = (date: Date) => {
  return date.toLocaleDateString();
};

// 添加搜索关键词
const searchKeyword = ref('')

// 搜索处理
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchArticles()
}

// 新增状态
const detailDrawerVisible = ref(false)
const currentArticle = ref<Article>({
  id: 0,
  type: '',
  title: '',
  content: '',
  created_at: '',
  author: '',
  date: new Date()
})

// 新增方法 - 打开详情抽屉
const showArticleDetail = (article: Article) => {
  currentArticle.value = article
  detailDrawerVisible.value = true
}

// 新增方法 - 获取标签类型
const getTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'admission': 'primary',
    'major': 'success',
    'exam': 'warning',
    'book': 'danger'
  }
  return typeMap[type] || 'info'
}
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.info-container {
  width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.article-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  /* 三列网格布局 */
  gap: 20px;
}

.article-card {
  transition: all 0.3s;
  width: 100%;
  /* 卡片宽度填满网格单元格 */
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .article-list {
    grid-template-columns: repeat(2, 1fr);
    /* 中等屏幕显示两列 */
  }
}

@media (max-width: 768px) {
  .article-list {
    grid-template-columns: 1fr;
    /* 小屏幕显示一列 */
  }
}

.article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  background-color: #D9AFD9;
  background-image: linear-gradient(0deg, #D9AFD9 0%, #97D9E1 100%);
}

.card-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
  position: relative;
  min-height: 130px;
  /* 为删除按钮定位 */
}

.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
  z-index: 1;
}

.type-tag {
  align-self: flex-start;
  padding: 2px 8px;
  background: var(--el-color-primary);
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.card-content {
  flex: 1;
  color: #666;
  line-height: 1.6;
}

.card-footer {
  margin-top: 15px;
  text-align: right;
  color: #999;
  font-size: 12px;
}

/* 不同类型卡片的不同边框颜色 */
.type-admission {
  border-top: 3px solid var(--el-color-primary);
}

.type-major {
  border-top: 3px solid var(--el-color-success);
}

.type-exam {
  border-top: 3px solid var(--el-color-warning);
}

.type-book {
  border-top: 3px solid var(--el-color-danger);
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.publish-button {
  margin-left: auto;
  /* 将发布按钮推到最右侧 */
}

/* 文章详情样式 */
.article-detail {
  padding: 20px;
}

.article-detail h2 {
  color: #333;
  margin-bottom: 15px;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.meta-info .date {
  color: #999;
  font-size: 14px;
}

.content {
  line-height: 1.8;
  color: #1b2c4d;
  white-space: pre-wrap;
  text-align: left; /* 添加左对齐样式 */
}
</style>